<template>
  <el-drawer
    v-model="visible"
    :title="formMode === 'create' ? '新增客户' : '编辑客户'"
    direction="rtl"
    size="600px"
    :before-close="handleClose"
    class="customer-edit-drawer"
  >
    <el-form
      ref="formRef"
      :model="form"
      :rules="rules"
      label-width="100px"
      class="customer-form"
    >
      <el-divider>基本信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户名称" prop="name">
            <el-input 
              v-model="form.name" 
              placeholder="请输入客户名称"
              class="form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户编码" prop="code">
            <el-input 
              v-model="form.code" 
              placeholder="请输入客户编码"
              class="form-input"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户类型" prop="type">
            <el-select 
              v-model="form.type" 
              placeholder="请选择客户类型"
              class="form-select"
            >
              <el-option label="企业客户" value="enterprise" />
              <el-option label="政府客户" value="government" />
              <el-option label="教育客户" value="education" />
              <el-option label="个人客户" value="individual" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户等级" prop="level">
            <el-select 
              v-model="form.level" 
              placeholder="请选择客户等级"
              class="form-select"
            >
              <el-option label="VIP客户" value="vip" />
              <el-option label="重要客户" value="important" />
              <el-option label="普通客户" value="normal" />
              <el-option label="新客户" value="new" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="客户状态" prop="status">
            <el-select 
              v-model="form.status" 
              placeholder="请选择客户状态"
              class="form-select"
            >
              <el-option label="合作中" value="active" />
              <el-option label="暂停合作" value="inactive" />
              <el-option label="风险客户" value="risk" />
              <el-option label="黑名单" value="blacklist" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户来源" prop="customerSource">
            <el-select 
              v-model="form.customerSource" 
              placeholder="请选择客户来源"
              class="form-select"
            >
              <el-option label="政采云" value="zcy" />
              <el-option label="推荐" value="referral" />
              <el-option label="自主开发" value="self" />
              <el-option label="其他" value="other" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-divider>联系人信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item label="联系人">
            <el-card 
              v-for="(contact, index) in form.contactPersons" 
              :key="contact.id || index" 
              class="contact-card"
              shadow="never"
            >
              <div class="contact-header">
                <span>联系人 {{ index + 1 }}</span>
                <el-button 
                  v-if="form.contactPersons.length > 1"
                  type="danger" 
                  link 
                  @click="removeContact(index)"
                  class="remove-btn"
                >
                  删除
                </el-button>
              </div>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item 
                    :prop="`contactPersons.${index}.name`" 
                    :rules="[{ required: true, message: '请输入联系人姓名', trigger: 'blur' }]"
                  >
                    <el-input 
                      v-model="contact.name" 
                      placeholder="联系人姓名"
                      class="form-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item>
                    <el-checkbox v-model="contact.isPrimary">主要联系人</el-checkbox>
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item>
                    <el-input 
                      v-model="contact.department" 
                      placeholder="部门"
                      class="form-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item>
                    <el-input 
                      v-model="contact.position" 
                      placeholder="职位"
                      class="form-input"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-row :gutter="20">
                <el-col :span="12">
                  <el-form-item>
                    <el-input 
                      v-model="contact.phone" 
                      placeholder="联系电话"
                      class="form-input"
                    />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item>
                    <el-input 
                      v-model="contact.email" 
                      placeholder="邮箱地址"
                      class="form-input"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              
              <el-form-item>
                <el-input 
                  v-model="contact.address" 
                  placeholder="联系地址"
                  class="form-input"
                />
              </el-form-item>
              
              <el-form-item>
                <el-input 
                  v-model="contact.remark" 
                  type="textarea"
                  placeholder="备注"
                  class="form-input"
                  :rows="2"
                />
              </el-form-item>
            </el-card>
            
            <el-button 
              type="primary" 
              link 
              @click="addContact"
              class="add-contact-btn"
            >
              <el-icon><Plus /></el-icon>
              添加联系人
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-divider>业务信息</el-divider>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="负责销售" prop="responsibleSalesman">
            <el-input 
              v-model="form.responsibleSalesman" 
              placeholder="请输入负责销售"
              class="form-input"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="信用评级" prop="creditRating">
            <el-select 
              v-model="form.creditRating" 
              placeholder="请选择信用评级"
              class="form-select"
            >
              <el-option label="A级" value="A" />
              <el-option label="B级" value="B" />
              <el-option label="C级" value="C" />
              <el-option label="D级" value="D" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="信用分数" prop="creditScore">
            <el-input-number 
              v-model="form.creditScore" 
              :min="0" 
              :max="100" 
              controls-position="right"
              class="form-input-number"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="客户价值" prop="customerValue">
            <el-rate
              v-model="form.customerValue"
              :max="5"
              show-score
              score-template="{value}星"
              class="form-rate"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="备注" prop="remark">
        <el-input 
          v-model="form.remark" 
          type="textarea"
          placeholder="请输入备注"
          class="form-textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="drawer-footer">
        <el-button @click="handleClose" class="cancel-btn">取消</el-button>
        <el-button 
          type="primary" 
          @click="handleSubmit" 
          :loading="submitLoading"
          class="submit-btn"
        >
          {{ formMode === 'create' ? '新增' : '保存' }}
        </el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
// @ts-nocheck
import { ref, watch, computed } from '@vue/runtime-core'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import type { Customer, ContactPerson } from '@/types/customer'
import { customerAPI } from '@/api/customer'

interface CustomerFormData {
  id: string
  name: string
  code: string
  type: string
  level: string
  status: string
  contactPersons: ContactPerson[]
  customerSource: string
  responsibleSalesman: string
  creditRating: string
  creditScore: number
  customerValue: number
  remark: string
  // 新增字段以匹配后端返回的数据结构
  customerType: string
  customerLevel: string
}

const props = defineProps<{
  modelValue: boolean
  formMode: 'create' | 'edit'
  customerData: Customer | null
}>()

const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'submit', data: Customer): void
  (e: 'close'): void
}>()

const visible = computed({
  get: () => props.modelValue,
  set: (value: boolean) => emit('update:modelValue', value)
})

const formRef = ref<FormInstance>()
const submitLoading = ref(false)

// 表单数据
const form = ref<CustomerFormData>({
  id: '',
  name: '',
  code: '',
  type: 'enterprise',
  level: 'normal',
  status: 'active',
  contactPersons: [{
    name: '',
    phone: '',
    email: '',
    isPrimary: true
  }],
  customerSource: 'self',
  responsibleSalesman: '',
  creditRating: 'A',
  creditScore: 80,
  customerValue: 3,
  remark: '',
  // 新增字段
  customerType: 'enterprise',
  customerLevel: 'normal'
})

// 表单验证规则
const rules = ref<FormRules>({
  name: [
    { required: true, message: '请输入客户名称', trigger: 'blur' }
  ],
  code: [
    { required: true, message: '请输入客户编码', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择客户类型', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择客户等级', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择客户状态', trigger: 'change' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
})

// 监听客户数据变化
watch(() => props.customerData, (newVal: Customer | null) => {
  if (newVal) {
    // 将后端数据映射到表单字段
    form.value = {
      id: newVal.id,
      name: newVal.name,
      code: newVal.code || '',
      type: newVal.type,
      level: newVal.level,
      status: newVal.status,
      contactPersons: newVal.contactPersons && newVal.contactPersons.length > 0 ? 
        newVal.contactPersons : [{
          name: '',
          phone: '',
          email: '',
          isPrimary: true
        }],
      customerSource: newVal.customerSource || 'self',
      responsibleSalesman: newVal.responsibleSalesman || '',
      creditRating: newVal.creditRating,
      creditScore: newVal.creditScore,
      customerValue: newVal.satisfactionScore ? Math.round(newVal.satisfactionScore / 20) : 3,
      remark: newVal.notes || '',
      // 新增字段
      customerType: newVal.type,
      customerLevel: newVal.level
    }
  } else {
    // 重置表单
    form.value = {
      id: '',
      name: '',
      code: '',
      type: 'enterprise',
      level: 'normal',
      status: 'active',
      contactPersons: [{
        name: '',
        phone: '',
        email: '',
        isPrimary: true
      }],
      customerSource: 'self',
      responsibleSalesman: '',
      creditRating: 'A',
      creditScore: 80,
      customerValue: 3,
      remark: '',
      // 新增字段
      customerType: 'enterprise',
      customerLevel: 'normal'
    }
  }
}, { immediate: true })

// 生成客户编码
const generateCustomerCode = () => {
  const prefixMap: Record<string, string> = {
    enterprise: 'ENT',
    individual: 'IND',
    government: 'GOV',
    education: 'EDU'
  }
  
  const prefix = prefixMap[form.value.type] || 'CUST'
  const date = new Date()
  const year = date.getFullYear()
  const month = (date.getMonth() + 1).toString().padStart(2, '0')
  const day = date.getDate().toString().padStart(2, '0')
  const random = Math.floor(Math.random() * 1000).toString().padStart(3, '0')
  
  return `${prefix}${year}${month}${day}${random}`
}

// 监听客户类型变化，自动生成编码
watch(() => form.value.type, (newVal: string) => {
  if (props.formMode === 'create' && !form.value.code) {
    form.value.code = generateCustomerCode()
  }
})

// 联系人操作方法
const addContact = () => {
  form.value.contactPersons.push({
    name: '',
    phone: '',
    email: '',
    isPrimary: false
  })
}

const removeContact = (index: number) => {
  if (form.value.contactPersons.length > 1) {
    form.value.contactPersons.splice(index, 1)
  } else {
    ElMessage.warning('至少需要保留一个联系人')
  }
}

// 方法
const handleClose = () => {
  emit('close')
  visible.value = false
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate((valid: boolean) => {
    if (valid) {
      submitLoading.value = true
      try {
        // 确保至少有一个主要联系人
        const hasPrimary = form.value.contactPersons.some((contact: ContactPerson) => contact.isPrimary)
        if (!hasPrimary && form.value.contactPersons.length > 0) {
          form.value.contactPersons[0].isPrimary = true
        }
        
        const submitData: any = {
          ...form.value,
          // 客户类型映射
          customerType: form.value.type === 'enterprise' ? '企业客户' : 
                       form.value.type === 'individual' ? '个人客户' : 
                       form.value.type === 'government' ? '政府客户' : '教育客户',
          // 客户等级映射
          customerLevel: form.value.level === 'vip' ? 'VIP' : 
                        form.value.level === 'important' ? '重要' : 
                        form.value.level === 'normal' ? '普通' : '潜在',
          // 客户状态映射：active-1, inactive-0
          status: form.value.status === 'active' ? 1 : 0
        }
        
        emit('submit', submitData)
        handleClose()
      } catch (error) {
        ElMessage.error(`${props.formMode === 'create' ? '新增' : '编辑'}客户失败`)
      } finally {
        submitLoading.value = false
      }
    }
  })
}
</script>

<style scoped>
.customer-edit-drawer {
  border-radius: 8px;
  overflow: hidden;
}

.customer-form {
  padding: 20px;
  max-height: calc(100vh - 120px);
  overflow-y: auto;
}

.contact-card {
  margin-bottom: 15px;
  border: 1px solid #ebeef5;
}

.contact-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  font-weight: bold;
}

.remove-btn {
  padding: 0;
}

.add-contact-btn {
  margin-top: 10px;
  padding: 0;
}

.drawer-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 16px 20px;
  border-top: 1px solid #ebeef5;
}

/* 表单元素悬停效果 */
.form-input:hover,
.form-select:hover,
.form-input-number:hover,
.form-textarea:hover {
  transform: translateY(-1px);
  transition: all 0.3s ease;
}

/* 取消按钮悬停效果 */
.cancel-btn {
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
}

.cancel-btn:hover {
  transform: translateY(-2px);
}
</style>